const colors = require('colors')
colors.setTheme({
  silly: 'rainbow',
  input: 'grey',
  verbose: 'cyan',
  prompt: 'grey',
  info: 'green',
  data: 'grey',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
})

const path = require('path')
console.log()
console.log(`> ${path.basename(__filename)}`.data + `开始运行了`.info)

//----------------------------------------------

array_data = [-2, 34, 5, 1234, 43, -55, 534, 2, 5, 52, 3, 35, 34, 523, 62, -314, 325, 36, 326, 54, 7]

// 傻逼都想得到的思路
// function addIndexFromTo(indexFromTo) {
//     console.log('索引:\t' + indexFromTo)
//     let index_from = indexFromTo[0]
//     let index_to = indexFromTo[1]

//     data = array_data.slice(index_from, index_to + 1)
//     console.log('所选数组:\t' + data)

//     return data.reduce((sum, current) => (sum += current), 0)
// }

// console.log(addIndexFromTo([0, 3]))
// console.log(addIndexFromTo([7, 18]))

// 前缀表思路
class NumArray {
  constructor(arr) {
    this._array = arr // 原数组
    this._preSum = [] // 前缀和表

    this.preSumCalculate = function () {
      let res = this._array.reduce((sum, current) => {
        this._preSum.push(sum)
        sum += current
        return sum
      }, 0)
      this._preSum = this._preSum.slice(1, this._preSum.length + 1)
      this._preSum.push(res)
    }
    this.preSumCalculate()
  }

  sumRange = function (indexFromTo) {
    let from = indexFromTo[0]
    let to = indexFromTo[1]
    return this._preSum[to] - this._preSum[from]
  }
}

let nA1 = new NumArray([1, 2, 3, 4, 5, 6])
// nA1.preSumCalculate()
console.log(nA1._array)
console.log(nA1._preSum)
console.log(nA1.sumRange([3, 5]))
